package com.infra.micro.id.domain.core;

import com.infra.micro.id.domain.config.BizConfig;
import com.infra.micro.id.domain.entity.IdWorkerPO;
import com.infra.micro.id.domain.service.IdWorkerService;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@MapperScan(basePackages = {"com.infra.micro.id.domain.mapper"})
public class IdGeneratorRunner implements ApplicationRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(IdGeneratorRunner.class);
    @Resource
    private IdWorkerService idWorkerService;
    @Resource
    private BizConfig bizConfig;
    protected ScheduledExecutorService scheduledExecutorService = null;

    @Override
    public void run(ApplicationArguments args) {
        LOGGER.info("项目初始开始");
        try {
            IdWorkerPO workerPO = idWorkerService.initWorkerServer();

            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(r -> {
                Thread thread = new Thread(r, "schedule-upload-time");
                thread.setDaemon(true);
                return thread;
            });
            scheduledExecutorService.scheduleWithFixedDelay(() -> idWorkerService.updateMaxTimestamp(workerPO.getWorkerId()), 1L, bizConfig.getDelaySeconds(), TimeUnit.SECONDS);
        } catch (Exception ex) {
            LOGGER.error("初始化工作节点数据时失败", ex);
        }
        LOGGER.info("项目启动完成");
    }
}
